local addon = LibStub("AceAddon-3.0"):GetAddon("Poppins")

local Group = {}
addon.Group = Group
local prototype = {}
Group.prototype = prototype
Group.metatable = { __index = prototype }
Group.callbacks = LibStub("CallbackHandler-1.0"):New(Group)

function Group:Create(group)
	local info = setmetatable({}, self.metatable)
	info.group = group
	info.options = addon.db.profile.groups[group]

	Group.callbacks:Fire("OnCreate", info, group)

	return info
end

function prototype:Destroy()
	Group.callbacks:Fire("OnDestroy", info, group)
	setmetatable(self, nil)
end

local function nextFrame(self, key)
	local frames = addon.buttons
	local group = self.group

	while true do
		local id, frame = next(frames, key)
		if (id and frame:GetGroup() == group) or id == nil then
			return id, frame
		else
			key = id
		end
	end
end

function prototype:IterateFrames()
	return nextFrame, self
end

function prototype:GetOption(option)
	local options = self.options
	if type(option) == "table" then
		for i, v in ipairs(option) do
			options = options[v]
		end
		return options
	else
		return options[option]
	end
end

function prototype:SetOption(option, value)
	local options = self.options
	if type(option) == "table" then
		for i, v in ipairs(option) do
			if i == #option then
				options[v] = value
			else
				options = options[v]
			end
		end
	else
		options[option] = value
	end
	self:UpdateOptions()
end

function prototype:ResetOptions()
	addon.db.profile.groups[self.group] = nil
	self.options = addon.db.profile.groups[self.group]
	self:UpdateOptions()
end

function prototype:UpdateOptions()
	for id, frame in self:IterateFrames() do
		frame:UpdateOptions()
	end
end